import { Injectable, OnModuleDestroy } from '@nestjs/common'
import Redis from 'ioredis'

@Injectable()
export class RedisService implements OnModuleDestroy {
  private readonly client: Redis

  constructor() {
    this.client = new Redis({
      host: process.env.REDIS_HOST,
      port: Number(process.env.REDIS_PORT || 6379),
      password: process.env.REDIS_PASSWORD,
      db: Number(process.env.REDIS_DB || 0),
    })
  }

  async set(key: string, value: any, ttl = 1800) {
    await this.client.set(key, JSON.stringify(value), 'EX', ttl)
  }

  async get(key: string) {
    const data = await this.client.get(key)
    return data ? JSON.parse(data) : null
  }

  async del(key: string) {
    await this.client.del(key)
  }

  async onModuleDestroy() {
    await this.client.quit()
  }
}
